package com.icehand.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.icehand.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * Created by icehand on 2017/5/12.
 */
@Configuration
public class MyWebAppConfiguer extends WebMvcConfigurerAdapter {

	/**
	 * 自定义静态资源
	 * @param registry
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry){
		registry.addResourceHandler("/images/**").addResourceLocations("classpath:/images/");
		super.addResourceHandlers(registry);
	}

	/**
	 * 自定义拦截器
	 * @param registry
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry){
		registry.addInterceptor(new MyInterceptor()).addPathPatterns("/*");
		super.addInterceptors(registry);
	}

	/**
	 * 利用fastjson替换jackson，且解决乱码问题
	 * @param converters
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		//处理中文乱码问题
		List<MediaType> fastMediaTypes = new ArrayList<>();
		fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		fastConverter.setSupportedMediaTypes(fastMediaTypes);
		fastConverter.setFastJsonConfig(fastJsonConfig);
		converters.add(fastConverter);

		StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
		List<MediaType> stringMediaTypes = new ArrayList<>();
		stringMediaTypes.add(MediaType.parseMediaType("text/plain;charset=UTF-8"));
		stringConverter.setSupportedMediaTypes(stringMediaTypes);
		converters.add(stringConverter);
	}

}
